var express = require('express')
var router = express.Router()
var mssqldb = require('../../Sql/Sql')

// 获取所有本账号记录
router.get('/api/record', function (req, res) {
  mssqldb.sql(`select * from Tallys where telephone=${req.query.telephone}`, function (err, result) {
    if (err) {
      console.log(err)
      let response = {
        errorCode: 1 // 错误
      }
      res.send(response)
      return
    }
    let response = {
      errorCode: 0, // 成功
      data: {
        result
      }
    }
    res.json(response)
  })
})

// 增加记录
router.put('/api/addition', function (req, res) {
  let account = ''
  mssqldb.sql(`select top 1 * from Accounts where id = ${req.body.account}`, function (err, result) {
    let count = parseFloat(result.recordset[0].expend) + parseFloat(req.body.expend)
    mssqldb.sql(`update Accounts set expend=${count} where telephone='${req.body.telephone}' and id = ${req.body.account}`, function (err, r) {
      if (err) {
        console.log(err)
        let response = {
          errorCode: 1 // 错误
        }
        res.send(response)
        return
      }
    })
    account = result.recordset[0].name
    mssqldb.sql(`insert into Tallys values('${req.body.telephone}','${req.body.date}',${req.body.expend},'${account}','${req.body.purpose}','${req.body.remark}')`, function (err, result) {
      if (err) {
        console.log(err)
        let response = {
          errorCode: 1 // 错误
        }
        res.send(response)
        return
      }
      let response = {
        errorCode: 0, // 成功
      }
      res.json(response)
    })
  })

})

// 修改记录
router.put('/api/revamp', function (req, res) {
  mssqldb.sql(`update Tallys set date='${req.body.date}',expend=${req.body.expend},account='${req.body.account}',purpose='${req.body.purpose}',remark='${req.body.remark}' where telephone='${req.body.telephone}' and id = ${req.body.id}`, function (err, result) {
    if (err) {
      console.log(err)
      let response = {
        errorCode: 1 // 错误
      }
      res.send(response)
      return
    }
    let response = {
      errorCode: 0, // 成功
    }
    res.json(response)
  })
})

// 删除记录
router.delete('/api/delete/:id', function (req, res) {
  mssqldb.sql(`delete from Tallys where id = ${req.params.id}`, function (err, result) {
    if (err) {
      console.log(err)
      let response = {
        errorCode: 1 // 错误
      }
      res.send(response)
      return
    }
    let response = {
      errorCode: 0, // 成功
    }
    res.json(response)
  })
})



module.exports = router